import 'package:flutter/material.dart';
import '../constants.dart';
import '../services/networking.dart';

class ChatScreen extends StatefulWidget {
  static const String id = 'chat_screen';

  @override
  _ChatScreenState createState() => _ChatScreenState();
}

Future getSendMessage({required String sender, required String text}) {
  NetworkHelper networkHelper = NetworkHelper();
  return networkHelper.sendMessage(sender: sender, text: text);
}

class _ChatScreenState extends State<ChatScreen> {
  String messageText = '';
  List<Map<String, dynamic>> messages = []; // 存储消息列表

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getMessageList();
  }

  // 获取消息列表
  void _getMessageList() async {
    NetworkHelper networkHelper = NetworkHelper();
    List<dynamic> messageList = await networkHelper.messageList();
    if (messageList.isNotEmpty) {
      setState(() {
        messages = messageList
            .cast<Map<String, dynamic>>()
            .reversed
            .toList(); // 更新消息列表
      });
    }
  }

  final TextEditingController _textcontroller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    // 获取传递的参数
    final Map<String, dynamic> args =
        ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;
    final String email = args['email'];
    print("邮箱：$email");

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        leading: null,
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.close),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ],
        title: Text('⚡️Chat'),
        backgroundColor: Colors.lightBlueAccent,
      ),
      body: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Expanded(
              child: messages.isEmpty
                  ? Center(
                      child: CircularProgressIndicator(
                        backgroundColor: Colors.lightBlueAccent,
                      ),
                    )
                  : ListView.builder(
                      itemCount: messages.length,
                      itemBuilder: (context, index) {
                        final message = messages[index];
                        final sender = message['sender'];
                        bool isMes = false;
                        if (sender == email) {
                          isMes = true;
                        }
                        return MessageBubble(
                          sender: message['sender'],
                          text: message['text'],
                          isMe: isMes,
                        );
                      },
                    ),
            ),
            Container(
              decoration: kMessageContainerDecoration,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Expanded(
                    child: TextField(
                      controller: _textcontroller,
                      keyboardType: TextInputType.text,
                      onChanged: (value) {
                        messageText = value;
                      },
                      decoration: kMessageTextFieldDecoration,
                    ),
                  ),
                  TextButton(
                    onPressed: () async {
                      dynamic send = await getSendMessage(
                        sender: email,
                        text: messageText,
                      );
                      if (send['code'] == 200) {
                        setState(() {
                          messageText = ''; // 清空输入框
                          _textcontroller.clear();
                        });
                        _getMessageList();
                      } else {}
                    },
                    child: Text('Send', style: kSendButtonTextStyle),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 消息气泡组件
class MessageBubble extends StatelessWidget {
  final String sender;
  final String text;
  final bool isMe;

  const MessageBubble({
    Key? key,
    required this.sender,
    required this.text,
    required this.isMe,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(10.0),
      child: Column(
        crossAxisAlignment: isMe
            ? CrossAxisAlignment.end
            : CrossAxisAlignment.start,
        children: <Widget>[
          Text(sender, style: TextStyle(fontSize: 12.0, color: Colors.black54)),
          Material(
            borderRadius: BorderRadius.circular(10.0),
            elevation: 5.0,
            color: isMe ? Colors.lightBlueAccent : Colors.white,
            child: Padding(
              padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
              child: Text(
                text,
                style: TextStyle(
                  color: isMe ? Colors.white : Colors.black54,
                  fontSize: 15.0,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
